//
//  MasterViewController.m
//  MusicOnline
//
//  Created by Le Thanh Hai on 6/9/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "MasterViewController.h"

#import "DetailViewController.h"

#import "NetworkConnection.h"

#import "PlayerViewController.h"

@interface MasterViewController () {
    NSMutableArray *titleArray;
    NSMutableArray *detailArray;
    NSArray* weekId;
}
@end

@implementation MasterViewController

@synthesize playerViewController = _playerViewController;
@synthesize detailViewController = _detailViewController;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = NSLocalizedString(@"Quick & Snow", @"Quick & Snow");
    }
    return self;
}
							
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:KEY_NOTIFICATION_NETWORK_FINISH object:nil];
    [titleArray release];
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    // self.navigationItem.leftBarButtonItem = self.editButtonItem;

    // UIBarButtonItem *addButton = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(insertNewObject:)] autorelease];
    // self.navigationItem.rightBarButtonItem = addButton;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receivedNetworkFinish:) name:KEY_NOTIFICATION_NETWORK_FINISH object:nil];
    
    NetworkConnection *con = [[NetworkConnection alloc] init];
    [con getAllListMusic];

}

#pragma mark network connect
-(void) receivedNetworkFinish:(NSNotification*) notification {
    NetworkConnection* networkCon = [notification object];
    
    if (!titleArray) {
        titleArray = [[NSMutableArray alloc] init];
    }
    
    if (!detailArray) {
        detailArray = [[NSMutableArray alloc] init];
    }
    
    NSArray *allKey = [networkCon.responseDic allKeys];    
    weekId = [allKey sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        if ([obj1 integerValue] > [obj2 integerValue]) {
            return (NSComparisonResult)NSOrderedDescending;
        }
        
        if ([obj1 integerValue] < [obj2 integerValue]) {
            return (NSComparisonResult)NSOrderedAscending;
        }
        return (NSComparisonResult)NSOrderedSame;
    }];
    
    for (int i = 0; i < [weekId count]; i++) {
        [titleArray insertObject:[[networkCon.responseDic objectForKey:[weekId objectAtIndex:i]] objectForKey:@"tile"] atIndex:i];
        [detailArray insertObject:[[networkCon.responseDic objectForKey:[weekId objectAtIndex:i]] objectForKey:@"datetime"] atIndex:i];
    }
    [weekId retain];
    [self.tableView reloadData];
    
    [appDelegate showBusyView:NO];
}     

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

- (void)insertNewObject:(id)sender
{
    if (!titleArray) {
        titleArray = [[NSMutableArray alloc] init];
    }
    [titleArray insertObject:@"Quick & Snow" atIndex:0];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}

#pragma mark - Table View

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return titleArray.count;
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }


    cell.textLabel.text = [titleArray objectAtIndex:[indexPath row]];
    cell.detailTextLabel.text = [detailArray objectAtIndex:[indexPath row]];
    cell.imageView.image = [UIImage imageNamed:@"icon.png"];
    [cell.imageView.layer setCornerRadius:4.0f];
    [cell.imageView.layer setMasksToBounds:YES];
    [cell.imageView.layer setBorderColor:[[UIColor cyanColor] CGColor]];
    [cell.imageView.layer setBorderWidth:1.0f];
    return cell;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row % 2)
    {
        [cell setBackgroundColor:[UIColor colorWithRed:.8 green:.8 blue:1 alpha:0.7]];
    }
    else [cell setBackgroundColor:[UIColor clearColor]];
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}

- (float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 61.333f;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [titleArray removeObjectAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }
}

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{    
//    if (!self.playerViewController) {
//          self.playerViewController = [[PlayerViewController alloc] initWithNibName:@"PlayerViewController" bundle:nil];
//    }
//    NSString *object = [titleArray objectAtIndex:indexPath.row];
//    NSLog(@"%@", object);
//    
//    NSString *url = @"http://tmp.mp3.stream.nixcdn.com/b60317c3bb5ff4c4c52bd409f734e878/4fe0b835/NhacCuaTui093/HayTraLoiEm-LeQuyen_kjw5.mp3";
//        
//    [self.playerViewController setupUrl:url andLyric:object];
    if (!self.detailViewController) {
        self.detailViewController = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:nil];
    }
    
    int i = [[weekId objectAtIndex:[indexPath row]] intValue];
    
    NSLog(@"%d", i);
//    NSString *wId = [NSString stringWithFormat:@"%d", i];
//    NetworkConnection* con = [[NetworkConnection alloc] init];
//    [con getAllDetailListMusic:wId];
//    
//    [self.detailViewController setTitle:@"Detail"];
//    [self.navigationController pushViewController:self.detailViewController animated:YES];
}

@end
